<?php
ptaste();
require_once(dirname(__FILE__)."/interfaces.php");


class JEngXRemote implements IJXmlProducer
{
	const METH_GET='GET';
	const METH_POST='POST';
	public $url=null;
	public $method=null;
	public $params=null;
	public $curl=null;
	public $logger=null;

	function __construct($url,$params,$method=self::METH_GET,$logger=null)
	{
	  $this->url=$url;
	  $this->params=$params;
	  $this->method=$method;
	  $this->logger=($logger)?$logger:new JEngNullLogger();
	}
	
	function prepare()
	{
	}
	
	function prepare_curl()
	{
	}
	
	function render()
	{
	  $this->curl=curl_init();
	  $this->prepare();
	  $ch=$this->curl;
	  curl_setopt($ch, CURLOPT_FAILONERROR, 1);  
	  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	  curl_setopt($ch, CURLOPT_TIMEOUT, 3);
	  $url=$this->url;
	  if ($this->method==self::METH_POST)
	  {
		curl_setopt($ch, CURLOPT_POST, 1);
		if ($this->params)
			curl_setopt($ch, CURLOPT_POSTFIELDS, $this->params);
	  }else{
	    if ($this->params)
		  foreach($this->params as $pname=>$pval)
		  {
			if (strpos($url,"?")==false)
			  $url.="?".urlencode($pname)."=".urlencode($pval);
			else
			  $url.="&".urlencode($pname)."=".urlencode($pval);
		  }
	  }
//	  printf("GETURL=%s<br>\n",$url);
	  $this->logger->debug("REMXML url:%s",$url);
	  curl_setopt($ch, CURLOPT_URL,$url);
	  $this->curl=$ch;
	  $this->prepare_curl();
	  $ch=$this->curl;
	  $result = curl_exec($ch);
	  curl_close($ch);
//	  printf("result=%s<br>\n",$result);
	  $this->logger->debug("REMXML res:%s",$result);
	  if (empty($result)) return null;
	  $xml=new DOMDocument();
	  $xml->loadXML($result);
	  $xml->encoding="utf8";
	  return $xml;
	}
	
	static function s_render()
	{
	  $url=func_get_arg(0);
	  $params=func_get_arg(1);
	  $method=JEngXRemote::METH_GET;
	  if (func_num_args()>2)
	    $method=func_get_arg(2);
	  $logger=null;
	  if (func_num_args()>3)
	    $logger=func_get_arg(3);
	  $obj=new JEngXRemote($url,$params,$method,$logger);
	  return $obj->render();
	}	
}

?>